home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 220 / 220.xpi / chrome / flashgot.jar / content / flashgot / flashgotHttpServer.js < prev    next >
Encoding:
Text File  |  2010-01-24  |  6.4 KB  |  213 lines

  1. /***** BEGIN LICENSE BLOCK *****
  2.  
  3.     FlashGot - a Firefox extension for external download managers integration
  4.     Copyright (C) 2004-2009 Giorgio Maone - g.maone@informaction.com
  5.  
  6.     This program is free software; you can redistribute it and/or modify
  7.     it under the terms of the GNU General Public License as published by
  8.     the Free Software Foundation; either version 2 of the License, or
  9.     (at your option) any later version.
  10.  
  11.     This program is distributed in the hope that it will be useful,
  12.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.     GNU General Public License for more details.
  15.  
  16.     You should have received a copy of the GNU General Public License
  17.     along with this program; if not, write to the Free Software
  18.     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  19.                              
  20. ***** END LICENSE BLOCK *****/
  21.  
  22. /* Data Swap HTTP server */
  23.  
  24. FlashGotHttpServer=function(fgService) {
  25.   this.fgService=fgService;
  26.   this.isDown=true;
  27.   this.serverSocket=Components.classes['@mozilla.org/network/server-socket;1'
  28.     ].createInstance(Components.interfaces.nsIServerSocket);
  29.   this.serverSocket.init(-1,true,-1);
  30.   this.isDown=false;
  31.   this.serverSocket.asyncListen(this);
  32.   this.tmpDir=this.fgService.tmpDir.clone();
  33.   this.tmpDir.append("httpserv");
  34.   this.logEnabled=fgService.getPref("LeechGet.httpLog",false);
  35.   this.log("Listening");
  36. }
  37.  
  38. FlashGotHttpServer.prototype={
  39.   documents: []
  40. ,
  41.   log: function(msg){
  42.     if(this.logEnabled && this.fgService.logEnabled) {
  43.       try {
  44.         if(!this.logStream) {
  45.           const logFile=this.tmpDir.clone();
  46.           logFile.append("server.log");
  47.           logFile.createUnique(0,0600);
  48.           const logStream=Components.classes["@mozilla.org/network/file-output-stream;1"
  49.             ].createInstance(Components.interfaces.nsIFileOutputStream );
  50.           logStream.init(logFile, 0x02 | 0x10, 0600, 0 );
  51.           this.logStream=logStream;
  52.         }
  53.         msg="HttpServer:"+this.serverSocket.port+" - "+msg+"\n";
  54.         this.logStream.write(msg,msg.length);
  55.         this.logStream.flush();
  56.       } catch(ex) {}
  57.     }
  58.   }
  59. ,
  60.   onSocketAccepted: function(ss,transport) {
  61.     this.log("Accepted request from "
  62.       +transport.host+":"+transport.port);
  63.      try {
  64.         new FlashGotHttpHandler(this,transport);
  65.      } catch(ex) {
  66.        this.log(ex.message);
  67.      }
  68.   }
  69. ,
  70.   onStopListening: function(ss,status) {
  71.     this.isDown=true;
  72.     if(this.logStream) {
  73.       this.log("Stopped, status "+status);
  74.     }
  75.   }
  76. ,
  77.   randomName: function(len) {
  78.     if(!len) len=8;
  79.     var name="";
  80.     for(var j=len; j-->0;) {
  81.       name+=String.fromCharCode(65+(Math.round(Math.random()*25)));
  82.     }
  83.     return name;
  84.   }
  85. ,
  86.   addDoc: function(docSource,docType) {
  87.     if (typeof(docType) == "undefined") docType="html";
  88.     var file=this.tmpDir.clone();
  89.     file.append(this.randomName() + "." + docType);
  90.     file.createUnique(0, 0600);
  91.     IO.writeFile(file, docSource);
  92.     const name=file.leafName;
  93.     this.documents.push(name);
  94.     return "http://localhost:" + this.serverSocket.port + "/" + name;
  95.   }
  96. ,
  97.   getDoc: function(name) {
  98.     const docs=this.documents;
  99.     for(var j=docs.length; j-->0;) {
  100.       if(docs[j]==name) break;
  101.     }
  102.     if(j<0) return null;
  103.     var file=this.tmpDir.clone();
  104.     file.append(name);
  105.     return file.exists() ? IO.readFile(file) : null;
  106.   }
  107. ,  
  108.   shutdown: function() {
  109.     try {
  110.       this.log("Shutting down");
  111.       if(this.logStream) {
  112.         this.logStream.close();
  113.         this.logStream=null;
  114.       }
  115.       this.serverSocket.close();
  116.     } catch(ex) {}
  117.   }
  118. }
  119.  
  120. function FlashGotHttpHandler(server,transport) {
  121.   this.server=server;
  122.   this.inputBuffer="";
  123.   this.transport=transport;
  124.   this.asyncStream=transport.openInputStream(0,0,0).QueryInterface(
  125.     Components.interfaces.nsIAsyncInputStream);
  126.   this.log("Waiting for request data...");
  127.   
  128.   const nsIThread=Components.interfaces.nsIThread;
  129.   var thread=Components.classes['@mozilla.org/thread;1'].createInstance(nsIThread);
  130.   thread.init(this, 0,  nsIThread.PRIORITY_NORMAL, nsIThread.SCOPE_GLOBAL,nsIThread.STATE_JOINABLE);
  131.   this.log("Thread started");
  132. }
  133.  
  134. FlashGotHttpHandler.prototype = {
  135.   log: function(msg) {
  136.     this.server.log(this.transport.host+":"+this.transport.port+" - "+msg);
  137.   }
  138. ,
  139.   run: function() {
  140.      this.log("I'm in thread");
  141.      this.asyncStream.asyncWait(this,0,0,null);
  142.      this.log("Asyncwait issued");
  143.   }
  144. ,  
  145.   onInputStreamReady: function(asyncStream) {
  146.     const bytesCount=asyncStream.available();
  147.     this.log("Input stream ready, available bytes: "+bytesCount);
  148.     if(bytesCount) {
  149.       const inStream=Components.classes['@mozilla.org/scriptableinputstream;1'].createInstance(
  150.         Components.interfaces.nsIScriptableInputStream);
  151.       inStream.init(asyncStream);
  152.       var chunk=inStream.read(inStream.available());
  153.       this.log("Received data chunk "+chunk);
  154.       var buffer=this.inputBuffer.concat(chunk);
  155.       var eor=chunk.length==0?buffer.length:buffer.search("\r?\n\r?\n");
  156.       this.log("EOR: "+eor);
  157.       if(eor>-1) {
  158.         var request=buffer.substring(0,eor);
  159.         this.inputBuffer="";
  160.         this.handleRequest(request);
  161.         this.close();
  162.       } else {
  163.         this.inputBuffer=buffer;
  164.         this.run();
  165.       }
  166.     } else {
  167.       this.close();
  168.     }
  169.   }
  170. ,
  171.   close: function() {
  172.     this.asyncStream.close();
  173.   }
  174. ,
  175.   buildResponse: function(body,status,contentType) {
  176.     if(!contentType) contentType="text/html";
  177.     if(!status) {
  178.       status="200 OK";
  179.     } else {
  180.       body="<h1>"+status+"</h1><pre>"
  181.         +body
  182.         +"</pre><h5>FlashGot Http Server v. 0.1</h5>"
  183.     }
  184.     return "HTTP/1.1 "+status+"\r\nContent-type: "+contentType+"\r\n\r\n"+body;
  185.   }
  186. ,
  187.   handleRequest: function(request) {
  188.     var response;
  189.     var match;
  190.     this.log("Handling request\n"+request);
  191.     try {
  192.       if(!(match=request.match(/^GET \/([^\s]*)/))) {
  193.         response=this.buildResponse(request,"400 Bad Request"); 
  194.       } else {
  195.         var doc=this.server.getDoc(match[1]);
  196.         
  197.         if(doc==null) {
  198.           response=this.buildResponse(request,"404 Not Found");
  199.         } else {
  200.           response=this.buildResponse(doc);
  201.         }
  202.       }
  203.     } catch(ex) {
  204.       response=this.buildResponse(ex.message+"\n"+request,"500 Server error");
  205.     }
  206.     var out=this.transport.openOutputStream(1,0,0);
  207.     out.write(response,response.length);
  208.     out.close();
  209.     this.log("Sent response\n"+response);
  210.   } 
  211. }
  212.  
  213.